Python 24-Day Course - Day 20: Virtual Environments and Dependencies

Day 20: Virtual Environments and Dependencies

Why Virtual Environments Are Needed

Different projects may require different library versions. Virtual environments create an independent Python environment for each project.

Creating a Virtual Environment with venv

# Create virtual environment
python -m venv myenv

# Activate (Windows)
myenv\Scripts\activate

# Activate (macOS/Linux)
source myenv/bin/activate

# Deactivate
deactivate

Package Management with pip

# Install a package
pip install requests

# Install a specific version
pip install requests==2.31.0

# List installed packages
pip list

# Generate requirements.txt
pip freeze > requirements.txt

# Install from requirements.txt
pip install -r requirements.txt

requirements.txt Example

requests==2.31.0
beautifulsoup4==4.12.2
python-dotenv==1.0.0

Project Structure Best Practices

my-project/
├── venv/              # Virtual environment (add to gitignore)
├── src/
│   └── main.py
├── tests/
│   └── test_main.py
├── .gitignore
├── .env.example       # Environment variable template
├── requirements.txt   # Dependency list
└── README.md

.gitignore Configuration

# Virtual environment
venv/
.venv/
env/

# Environment variables
.env

# Python cache
__pycache__/
*.pyc
*.pyo

# IDE
.vscode/
.idea/

Environment Variable Management

# .env.example (committed)
# API_KEY=
# DATABASE_URL=

# .env (not committed)
# API_KEY=sk-xxxx
# DATABASE_URL=sqlite:///myapp.db

from dotenv import load_dotenv
import os

load_dotenv()
api_key = os.getenv("API_KEY")
db_url = os.getenv("DATABASE_URL", "sqlite:///default.db")

Today’s Exercises

  1. Create a virtual environment for a new project, install necessary packages, and generate requirements.txt.
  2. Write a program that reads settings from an .env file.
  3. Reproduce a situation where two projects use different versions of the same library.

Was this article helpful?